#include "stdafx.h"
#include "ui.h"
namespace ui
{	
	const int STARTUP_WIDTH = 800;
	const int STARTUP_HEIGHT = 600;
	void set_color(UI ui, int x, int y, unsigned char r, unsigned char g, unsigned char b)
	{
		unsigned int* pix = (unsigned int*) ((ui.framebuffer_data) + (y * ui.pitch) + 4 * x);
		*pix = (0 << 24 | r << 16 | g << 8 | b);
	}
	void update_time_per_frame(UI ui, float time)
	{
		char str[200];
		sprintf_s(str, "Time / Frame = %f", time);
		SDL_SetWindowTitle(ui.window, str);
	}
	UI init()
	{
		assert(SDL_Init(SDL_INIT_EVERYTHING) == 0);
		UI ui;
		ui.window = SDL_CreateWindow("Rayca", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, STARTUP_WIDTH, STARTUP_HEIGHT,
			SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
		assert(ui.window != nullptr);
		ui.renderer = SDL_CreateRenderer(ui.window, -1, 0);
		assert(ui.renderer != nullptr);
		ui.framebuffer = SDL_CreateTexture(ui.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, STARTUP_WIDTH, STARTUP_HEIGHT);
		assert(ui.framebuffer != nullptr);

		ui.w = STARTUP_WIDTH;
		ui.h = STARTUP_HEIGHT;
		return ui;
	}
	//returns whether we should quit
	bool process_events(UI& ui)
	{	
		SDL_Event event;
		while( SDL_PollEvent( &event ) )
		{
			if(event.type == SDL_QUIT) return true;
			if(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED)
			{
				SDL_DestroyTexture(ui.framebuffer);
				SDL_DestroyRenderer(ui.renderer);
				ui.renderer = SDL_CreateRenderer(ui.window, -1, 0);
				ui.framebuffer = nullptr;
				ui.framebuffer = SDL_CreateTexture(ui.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, event.window.data1, 
					event.window.data2);
				ui.w = event.window.data1;
				ui.h = event.window.data2;
			}
		}
		return false;
	}
	void begin_frame(UI& ui)
	{	
		ui.framebuffer_data = nullptr;
		ui.pitch = 0;
		assert(SDL_SetRenderDrawColor(ui.renderer, 255, 0, 0, 1) == 0);
		assert(SDL_RenderClear(ui.renderer) == 0);
		assert(SDL_LockTexture(ui.framebuffer, nullptr, (void**)&ui.framebuffer_data, &ui.pitch) == 0);
	}
	void end_frame(UI ui)
	{
		SDL_UnlockTexture(ui.framebuffer);
		SDL_RenderCopy(ui.renderer, ui.framebuffer, nullptr, nullptr);
		SDL_RenderPresent(ui.renderer);
	}
	void quit(UI ui)
	{
		SDL_DestroyTexture(ui.framebuffer);
		SDL_DestroyRenderer(ui.renderer);
		SDL_DestroyWindow(ui.window);
		SDL_Quit();
	}
}